﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using Cinema.Model.Entities.BaseEntities;
using Cinema.Model.Interfaces;

namespace Cinema.Model.EF.Repositories
{
    public abstract class GenericRepository<T> : IRepository<T>
        where T : IdentifiableEntityBase
    {
        protected CinemaContext _cinemaContext;

        public GenericRepository(CinemaContext ctx)
        {
            _cinemaContext = ctx;
        }

        public abstract DbSet<T> EntitySet { get; protected set; }

        public T Create(T entity)
        {
            return EntitySet.Add(entity);
        }

        public T Update(T entity)
        {
            _cinemaContext.Entry(entity).State = EntityState.Modified;
            return entity;
        }

        public void Delete(T entity)
        {
            EntitySet.Remove(entity);
        }

        public T Read(int id)
        {
            return EntitySet.Single(x => x.Id == id);
        }

        public IQueryable<T> Read()
        {
            return EntitySet;
        }

        public void DeleteById(int id)
        {
            EntitySet.Remove(this.Read(id));
        }
    }
}
